<?php
namespace control;
/*
*计件工资类
*/

class pieceCountClass extends adIndexClass
{
    private const page = 'pieceCount';
    private const title = '计件工资';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        $isProductCard = optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard';
        switch ($fun) {
            default:
                $tr = [
                    'teamNo'          => [
                        'name'  => "日期",
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'orderNo'  => [
                        'name'  => $isProductCard?'生产流转卡':'派工单号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'machiningOrder'         => [
                        'name'  => '生产计划单号',
                        'width' => 150,
                    ],
                    'process'          => [
                        'name'  => '工序',
                        'width' => 150,
                    ],
                    'valuationType'          => [
                        'name'  => '计价方式',
                        'width' => 100,
                    ],
                    'teamType'          => [
                        'name'  => '班次',
                        'width' => 100,
                    ],
                    'team'          => [
                        'name'  => '班组',
                        'width' => 150,
                    ],
                    'teamStid'          => [
                        'name'  => '员工',
                        'width' => 100,
                    ],
                    'code'          => [
                        'name'  => '产品编码',
                        'width' => 150,
                    ],
                    'name'          => [
                        'name'  => '产品名称',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unti'          => [
                        'name'  => '计件单位',
                        'width' => 70,
                    ],
                    'yield'          => [
                        'name'  => '产量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'price'          => [
                        'name'  => '计件单价',
                        'width' => 100,
                    ],
                    'salary'          => [
                        'name'  => '计件工资合计',
                        'width' => 150,
                    ],
                    'personMoney'          => [
                        'name'  => '个人分得计件工资',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "报工单号" => text(array("name" => "orderNo")),
                    "班组"   => selectMultiple(array("name" => "teamId", 'where'=>"coid = '".self::$coid."'","table" => "team",  'sqlField' => 'name', 'sqlId' => 'id', 'class' => 'width200')),
                    '班次' => select(array('name' => 'teamType', 'option' => explode('，', para('teamType')))),
                ],
                [
                    '员工'  => selectMultiple(array("name" => "stid", "table" => "staff",  'sqlField' => 'name', 'sqlId' => 'stid', 'class' => 'width200')),
                    "日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "b.orderNo"=>$this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            "b.classify"=>'工序报工',
            "b.coid"=>self::$coid,
            "b.state"=>'已确认',
            "a.stid"=>$this->post('stid'),
            "b.teamId"=>$this->post('teamId'),
            "b.teamType"=>$this->post('teamType')
        );
        $and ="";
        if ($this->post('createTime')) {
            $and.=self::timeComparison($this->post('createTime'),field: 'teamNo');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'b.teamNo desc,a.list',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => "process_report_staff as a join process_report as b on a.orderId = b.id",
            'field'=>"b.*,a.stid as teamStid",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        static::rSet(self::$stid.self::page.'Sql', $page['fullSql']);
        $isProductCard = optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard';
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            if ($isProductCard){
                $machining_card_detail = query('machining_card_detail',"id = '$array[sendId]'");
                $sourceOrder = query('machining_card',"id = '$machining_card_detail[orderId]'");
                $machiningOrderMx = query('machining_order_mx',"id = '$sourceOrder[sourceMxId]'");
            }else{
                $sourceOrder = query('machining_send_order',"id = '$array[sendId]'");
                $machiningOrderMx = query('machining_order_mx',"id = '$sourceOrder[machiningOrderMxId]'");
            }

            $material = query('material',"id = '$array[materialId]'");
            $routMx = query('routing_detail',"id = '$array[routingMxId]'");
            $routMx['price']=$routMx['price']?:0;
            $process = query('process',"id = '$array[processId]'");
            $array['yield'] = machiningOrderClass::material_num_change($array['materialId'],$sourceOrder['unit'],$material['unit'],$array['yield']);
            $salary = self::formattingFigure($routMx['price']*$array['yield']);

            if ($array['valuationType'] =='个人计件'){
                $personMoney = $salary;
            }else{
                $team_detail = query('team_detail',"orderId = '$array[teamId]' and stid = '$array[teamStid]'");
                $team_detail['rate'] = $team_detail['rate']?:0;
                //当前班组人员考勤
                $workshop_clock_detail = find(array('table'=>'workshop_clock as a join workshop_clock_detail as b on a.id = b.orderId','single'=>"a.state !='草稿' and a.teamId like '%$array[teamId]%' and b.stid = '$array[teamStid]' and b.recordDate = '$array[teamNo]'",'field'=>"b.hour"));
                $workshop_clock_detail['hour'] = $workshop_clock_detail['hour']??0;
                $rateSum = $this->caculate($array['teamId'],$array['teamNo']);
                //公式  计件工资*（个人计件系数*个人考勤）/(班组中每个人的(个人考勤*个人系数)之和)
                $personMoney =$rateSum>0? round($salary*($team_detail['rate']*$workshop_clock_detail['hour']/$rateSum),2):0;
            }
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'sourceOrder':
                        $row[] = $sourceOrder['orderNo'];
                        break;
                    case 'machiningOrder':
                        $machiningOrder = query('machining_order',"id = '$machiningOrderMx[orderId]'");
                        $row[] = $machiningOrder['orderNo'];
                        break;
                    case 'process':
                        $row[] = $process['name'];
                        break;
                    case 'valuationType':
                    case 'price':
                        $row[] = $routMx[$key];
                        break;
                    case 'team':
                        $team = query('team',"id = '$array[teamId]'");
                        $row[] = $team['name'];
                        break;
                    case 'teamStid':
                        $row[] = self::findStaff($array['teamStid']);
                        break;
                    case 'code':
                    case 'name':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    case 'yield':
                        $row[] = self::lostZero($array['yield'],'numPrecision');
                        break;
                    case 'salary':
                        $row[] = $salary;
                        break;
                    case 'personMoney':
                        $row[] = $personMoney;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => "process_report_staff as a join process_report as b on a.orderId = b.id join material as c on c.id = b.materialId join routing_detail as mx on mx.id = b.routingMxId",
            'single' => $where,
            'field'  => "ifnull(SUM((CASE WHEN b.unit = c.unit_one THEN b.yield*c.unit_one_num WHEN b.unit = c.unit_two THEN b.yield*c.unit_two_num ELSE b.yield END)/(CASE WHEN b.unit = c.unit_one THEN c.unit_one_num WHEN b.unit = c.unit_two THEN c.unit_two_num ELSE 1 END)),0) AS yield,ifnull(SUM((CASE WHEN b.unit = c.unit_one THEN b.yield*c.unit_one_num WHEN b.unit = c.unit_two THEN b.yield*c.unit_two_num ELSE b.yield END)/(CASE WHEN b.unit = c.unit_one THEN c.unit_one_num WHEN b.unit = c.unit_two THEN c.unit_two_num ELSE 1 END)*mx.price),0) AS money",
        ]);
        $total    = [
            'yield'        => self::lostZero($totalQuery['yield'], 'numPrecision'),
            'salary'        => self::formattingFigure($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 计算 计件系数和计件工时和
     */
    public function caculate($teamId,$date): float|int
    {
        $total = 0;
        $team_detail = find(array('table'=>'team_detail','where'=>"orderId = '$teamId'"));
        foreach ($team_detail['array'] as $array){
            $workshop_clock_detail = find(array('table'=>'workshop_clock as a join workshop_clock_detail as b on a.id = b.orderId','single'=>"a.state !='草稿' and a.teamId like '%$teamId%' and b.stid = '$array[stid]' and b.recordDate = '$date'",'field'=>"b.hour"));
            $workshop_clock_detail['hour'] = $workshop_clock_detail['hour']??0;
            $total+=$array['rate']*$workshop_clock_detail['hour'];
        }
        return $total;
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $isProductCard = optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard';
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => "process_report_staff as a join process_report as b on a.orderId = b.id",
                    'field'=>"b.*,a.stid as teamStid",
                    "where" => "b.id in ('".implode("','", $checkedId)."') order by b.teamNo desc,a.list desc",
                ))['array'];
            }else{
                $sql = static::rGet(self::$stid.self::page.'Sql');
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                if ($isProductCard){
                    $machining_card_detail = query('machining_card_detail',"id = '$array[sendId]'");
                    $sourceOrder = query('machining_card',"id = '$machining_card_detail[orderId]'");
                    $machiningOrderMx = query('machining_order_mx',"id = '$sourceOrder[sourceMxId]'");
                }else{
                    $sourceOrder = query('machining_send_order',"id = '$array[sendId]'");
                    $machiningOrderMx = query('machining_order_mx',"id = '$sourceOrder[machiningOrderMxId]'");
                }

                $team = query('team',"id = '$array[teamId]'");
                $material = query('material',"id = '$array[materialId]'");

                $machiningOrder = query('machining_order',"id = '$machiningOrderMx[orderId]'");
                $routMx = query('routing_detail',"id = '$array[routingMxId]'");
                $routMx['price']=$routMx['price']?:0;
                $process = query('process',"id = '$array[processId]'");
                $array['yield'] = machiningOrderClass::material_num_change($array['materialId'],$sourceOrder['unit'],$material['unit'],$array['yield']);
                $salary = self::formattingFigure($routMx['price']*$array['yield']);

                if ($array['valuationType'] =='个人计件'){
                    $personMoney = $salary;
                }else{
                    $team_detail = query('team_detail',"orderId = '$array[teamId]' and stid = '$array[teamStid]'");
                    $team_detail['rate'] = $team_detail['rate']?:0;
                    //当前班组人员考勤
                    $workshop_clock_detail = find(array('table'=>'workshop_clock as a join workshop_clock_detail as b on a.id = b.orderId','single'=>"a.state !='草稿' and a.teamId like '%$array[teamId]%' and b.stid = '$array[teamStid]' and b.recordDate = '$array[teamNo]'",'field'=>"b.hour"));
                    $workshop_clock_detail['hour'] = $workshop_clock_detail['hour']??0;
                    $rateSum = $this->caculate($array['teamId'],$array['teamNo']);
                    //公式  计件工资*（个人计件系数*个人考勤）/(班组中每个人的(个人考勤*个人系数)之和)
                    $personMoney =$rateSum>0? round($salary*($team_detail['rate']*$workshop_clock_detail['hour']/$rateSum),2):0;
                }
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '日期'=>$array['teamNo'],
                            '报工单号'=>$array['orderNo'],
                            '生产流转卡号/派工单号'=>$sourceOrder['orderNo'],
                            '生产计划单号'=>$machiningOrder['orderNo'],
                            '工序'=> $process['name'],
                            '计价方式'=>$routMx['valuationType'],
                            '班次'=>$array['teamType'],
                            '班组'=> $team['name'],
                            '员工'=>self::findStaff($array['teamStid']),
                            '产品编码'=>$material['code'],
                            '产品名称'=> $material['name'],
                            '规格型号'=> $material['model'],
                            '计件单位'=>$material['unit'],
                            '产量'=>self::lostZero($array['yield'],'numPrecision'),
                            '计件单价'=>$routMx['price'],
                            '计件工资合计'=>$salary,
                            '个人分得计件工资'=>$personMoney,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了计件工资表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "计件工资表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'日期',
                    'aliasName'=>'日期',
                ],
                [
                    'columnName'=>'报工单号',
                    'aliasName'=>'报工单号',
                ],
                [
                    'columnName'=>'生产流转卡号/派工单号',
                    'aliasName'=>'生产流转卡号/派工单号',
                ],
                [
                    'columnName'=>'生产计划单号',
                    'aliasName'=>'生产计划单号',
                ],
                [
                    'columnName'=>'工序',
                    'aliasName'=>'工序',
                ],
                [
                    'columnName'=>'计价方式',
                    'aliasName'=>'计价方式',
                ],
                [
                    'columnName'=>'班次',
                    'aliasName'=>'班次',
                ],
                [
                    'columnName'=>'班组',
                    'aliasName'=>'班组',
                ],
                [
                    'columnName'=>'员工',
                    'aliasName'=>'员工',
                ],
                [
                    'columnName'=>'产品编码',
                    'aliasName'=>'产品编码',
                ],
                [
                    'columnName'=>'产品名称',
                    'aliasName'=>'产品名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'计件单位',
                    'aliasName'=>'计件单位',
                ],
                [
                    'columnName'=>'产量',
                    'aliasName'=>'产量',
                ],
                [
                    'columnName'=>'计件单价',
                    'aliasName'=>'计件单价',
                ],
                [
                    'columnName'=>'计件工资合计',
                    'aliasName'=>'计件工资合计',
                ],
                [
                    'columnName'=>'个人分得计件工资',
                    'aliasName'=>'个人分得计件工资',
                ],
            ]
        };
    }
}

